/**
 * 
 */
package com.htht.tourism.action;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import net.sf.json.JSONObject;

import org.jdom.JDOMException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.htht.tourism.domain.Response;
import com.htht.tourism.domain.User;
import com.htht.tourism.domain.WeChatInfo;
import com.htht.tourism.domain.WeixinUser;
import com.htht.tourism.domain.link.Activity_signParam;
import com.htht.tourism.domain.link.UserParam;
import com.htht.tourism.intf.TUserService;
import com.htht.tourism.intf.impl.ActivitySignServiceImpl;
import com.htht.tourism.utils.ConfigUtil;
import com.htht.tourism.utils.DateUtil;
import com.htht.tourism.utils.GsonUtils;
import com.htht.tourism.utils.HttpUtil;
import com.htht.tourism.utils.ValidatorResultHandler;
import com.htht.tourism.utils.WXJSPay;
import com.htht.tourism.utils.WeixinHelper;
import com.htht.tourism.utils.XMLUtil;

/**
 * @author wuqiwei
 *
 */
@Controller
@ResponseBody
@RequestMapping("/wechat")
public class WeChatController {
	@Resource
	private TUserService tUserService;
	@Resource
	private ActivitySignServiceImpl activitySignServiceImpl;
	/**
	 * 获取openid
	 * @author:wuqiwei
	 * @param @param param
	 * @param @param result
	 * @param @return
	 * @throws IOException 
	 * @throws ServletException 
	 * @date:2017年3月27日下午2:35:13
	 */
	
	@RequestMapping(value = "/getOpenid",produces="text/html;charset=UTF-8;", method = RequestMethod.GET)
	public ModelAndView add(final HttpServletRequest request,final HttpServletResponse response) throws ServletException, IOException {
		WxMpUser wxMpUser =  null;
		Map model = new HashMap();
		try {
//			System.out.println(request.getParameter("code"));
			String appid = WeixinHelper.APPID;
			String appsecret = WeixinHelper.APPSECRET;
			String code = request.getParameter("code");
			WxMpOAuth2AccessToken wxMpOAuth2AccessToken = WeixinHelper.getWxMpService().oauth2getAccessToken(request.getParameter("code"));
			wxMpUser =  WeixinHelper.getWxMpService().oauth2getUserInfo(wxMpOAuth2AccessToken, null);
			
			//获取openId和access_token（获取openId后调用统一支付接口https://api.mch.weixin.qq.com/pay/unifiedorder）
	        String openId = wxMpUser.getOpenId();
//	        String access_token = "";
//	        String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
//	    	String sq = HttpUtil.getInstance().doGet(URL);
//	    	WeChatInfo  bean= (WeChatInfo) GsonUtils.getInstance().fromJson(sq, WeChatInfo.class);
//	        if (null != bean) {
//	            access_token = bean.getAccess_token();
//	        }
	        //获取用户信息
//	        String nickname = "";
//	        String headimgurl = "";
//	        String userURL = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"";
//	        String userJson =  HttpUtil.getInstance().doGet(userURL);
//	        WeixinUser user = (WeixinUser) GsonUtils.getInstance().fromJson(userJson, WeixinUser.class);
//	        if (null != user) {
//	            nickname = user.getNickname();
//	            headimgurl = user.getHeadimgurl();
//	        }
	        model.put("openid", openId);
//	        model.put("nickname", nickname);
//	        model.put("headimgurl", headimgurl);
		} catch (Exception e) {
			e.printStackTrace();
		}
		ModelAndView mav = new ModelAndView("/tshd/tshd",model);
		return mav;
	}
	
	/**
	 * 微信支付
	 * @author:wuqiwei
	 * @param @param request
	 * @param @param response
	 * @param @return
	 * @param @throws ServletException
	 * @param @throws IOException
	 * @date:2017年4月5日上午10:45:42
	 */
	@RequestMapping(value = "/WeChatPay",produces="text/html;charset=UTF-8;", method = RequestMethod.GET)
	public String WeChatPay(final HttpServletRequest request,final HttpServletResponse response) throws ServletException, IOException {
		//网页授权后获取传递的参数
        String money = request.getParameter("money");//分为单位
        String activity= request.getParameter("activity_id");//活动id
        String appid  =  request.getParameter("appid");//appid
        String time  = request.getParameter("time");//time
        String state = request.getParameter("state");//state
        String result = "";
        //金额转化为分为单位
//        float sessionmoney = Float.parseFloat(money);
//        String finalmoney = String.format("%.2f", sessionmoney);
//        finalmoney = finalmoney.replace(".", "");
//        System.out.println("money"+finalmoney);
		String openid = request.getParameter("openId");
//		System.out.println("openid"+openid);
          String outTradeNum = System.currentTimeMillis() + ""; // 商户订单号
          //先插入一条报名记录 state为0
          Activity_signParam param = new Activity_signParam();
          param.setActivity_id(Long.valueOf(activity));
          param.setAppid(appid);
          param.setTradeno(outTradeNum);
          param.setTime(time);
          param.setState(0);
         if(money.equalsIgnoreCase("0")){//当金额为0时 不访问微信
        	 param.setState(1);
        	 activitySignServiceImpl.sign(param);//报名
        	 result = "报名成功";
         }
         activitySignServiceImpl.sign(param);//报名
          Map<String, String> wxPayParamMap = null;
          try {
              wxPayParamMap = WXJSPay.jsApiPay(openid, money, outTradeNum,UUID.randomUUID().toString()); // 测试金额为1分钱
          } catch (JDOMException e) {
              e.printStackTrace();
          }
          JSONObject json = JSONObject.fromObject(wxPayParamMap); 
          result = json.toString();
          System.out.println(result);
          return result;
	}
	 /**
     * 支付回调
     * 
     * @throws IOException
     * @throws JDOMException
     */
    @RequestMapping(value = "callback", method = RequestMethod.POST)
    public void callback(final HttpServletRequest request, final HttpServletResponse response) throws JDOMException {
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String resultStr = new String(outSteam.toByteArray(), "utf-8");
            Map<String, String> resultMap = XMLUtil.doXMLParse(resultStr);
            String outTradeNo = resultMap.get("out_trade_no");
            String transactionId = resultMap.get("transaction_id"); // 微信支付订单号
            // String sign = resultMap.get("sign");
            String returnCode = resultMap.get("return_code"); // 签名验证
            String openid = resultMap.get("openid"); // 用户标识
            Activity_signParam param = new Activity_signParam();
            param.setTradeno(outTradeNo);
            if (returnCode.equals("SUCCESS")) {
                SortedMap<String, String> sm = new TreeMap<String, String>();
                sm.put("return_code", "SUCCESS"); // 告诉微信服务器，我收到信息了，不要在调用回调action了,
                sm.put("return_msg", "OK");
                String backString = XMLUtil.getRequestXml(sm);
                response.getWriter().write(backString); // 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
                int a = activitySignServiceImpl.updateState(param);//如果支付成功修改状态
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
    	  SortedMap<Object, Object> wxPayParamMap = new TreeMap<Object, Object>();
          wxPayParamMap.put("appId",ConfigUtil.getProperty("WeChat","appid"));
          wxPayParamMap.put("timeStamp", "111");
          wxPayParamMap.put("nonceStr", "22222");
          JSONObject json = JSONObject.fromObject(wxPayParamMap); 
          System.out.println("111111"+json);
	}
}
